<template>
  <div id="login-container">
    <div style="text-align: center;height: 50px">
      博客管理登录
    </div>
    <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
      <el-form-item label="账号" prop="user">
        <el-input type="text" v-model="ruleForm.user" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="pass">
        <el-input type="password" v-model="ruleForm.pass" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
  // import axios from 'axios'
  export default {
    name: "login",
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入账号'));
      } else {
        if (this.ruleForm.pass !== '') {
          this.$refs.ruleForm.validateField('pass');
        }
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else {
        callback();
      }
    };
    return {
      ruleForm: {
        user: '',
        pass: ''
      },
      rules: {
        user: [
          { validator: validatePass, trigger: 'blur' }
        ],
        pass: [
          { validator: validatePass2, trigger: 'blur' }
        ]
      },
      isLogin:false
    };
  },
  methods: {
    submitForm(formName) {
	  var that=this
	  //判断用户是否输入账号与密码
	  if(this.ruleForm.user!=''&&this.ruleForm.pass!=''){
		//向后端发送登录请求
		this.axios.get("http://"+that.$store.state.host+":8181/user/findByid/"+this.ruleForm.user+"/"+this.ruleForm.pass).then(function(res){
			// console.log(res);
			//根据后端返回的状态查看账号是否正确
			if(res.data.status==true){
				//调用mutations中的addUser方法  通过store保存用户信息 (其实没啥用)
				that.$store.commit("addUser",that.ruleForm.user,that.ruleForm.pass);
				//使用sessionStorage保存用户的登录状态与用户的信息
				sessionStorage.setItem("user_login",1)
				sessionStorage.setItem("user_info",JSON.stringify(res.data.map.Login_user))
				//登录成功后跳转到后台的个人信息界面
				that.$message.success("登录成功!");
				that.$router.push({path: "/mysels_information"});
			}else{
				that.$message.error(res.data.message);
			}
		})
	  }else{
		that.$message.error("请输入账号和密码!!!");
	  }
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  }
  }
</script>

<style scoped>
  body{
    margin: 0;
  }
  #login-container{
    width: 400px;
    height: 290px;
    background: #e5e9f2;
    position: absolute;
    left: 50%;
    top: 50%;
    margin-left: -220px;
    margin-top: -170px;
    border-radius: 5px;
    padding-top: 40px;
    padding-right: 40px;
  }
</style>
